import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { v4 as uuidv4 } from 'uuid'

export const useEditorStore = defineStore('editor', () => {
  // 画布上的组件列表
  const components = ref([])

  // 当前选中的组件ID
  const selectedComponentId = ref(null)

  // 画布配置
  const canvasConfig = ref({
    width: '100%',
    height: '100vh',
    backgroundColor: '#f5f5f5',
    padding: '20px',
  })

  // 缩放配置
  const zoomConfig = ref({
    level: 1,
    min: 0.1,
    max: 3,
    step: 0.1,
  })

  // 页面配置
  const pageConfig = ref({
    title: '未命名页面',
    description: '',
    created: new Date().toISOString(),
  })

  // 计算当前选中的组件
  const selectedComponent = computed(() => {
    return components.value.find((comp) => comp.id === selectedComponentId.value)
  })

  // 添加组件到画布
  const addComponent = (componentType, position = { x: 100, y: 100 }) => {
    const newComponent = {
      id: uuidv4(),
      type: componentType,
      position,
      props: getDefaultProps(componentType),
      styles: getDefaultStyles(componentType),
    }
    components.value.push(newComponent)
    selectedComponentId.value = newComponent.id
    return newComponent
  }

  // 删除组件
  const removeComponent = (componentId) => {
    const index = components.value.findIndex((comp) => comp.id === componentId)
    if (index > -1) {
      components.value.splice(index, 1)
      if (selectedComponentId.value === componentId) {
        selectedComponentId.value = null
      }
    }
  }

  // 更新组件属性
  const updateComponentProps = (componentId, props) => {
    const component = components.value.find((comp) => comp.id === componentId)
    if (component) {
      component.props = { ...component.props, ...props }
    }
  }

  // 更新组件样式
  const updateComponentStyles = (componentId, styles) => {
    const component = components.value.find((comp) => comp.id === componentId)
    if (component) {
      component.styles = { ...component.styles, ...styles }
    }
  }

  // 更新组件位置
  const updateComponentPosition = (componentId, position) => {
    const component = components.value.find((comp) => comp.id === componentId)
    if (component) {
      component.position = { ...component.position, ...position }
    }
  }

  // 选中组件
  const selectComponent = (componentId) => {
    selectedComponentId.value = componentId
  }

  // 清空选中
  const clearSelection = () => {
    selectedComponentId.value = null
  }

  // 清空画布
  const clearCanvas = () => {
    components.value = []
    selectedComponentId.value = null
  }

  // 保存页面
  const savePage = (name = '未命名页面') => {
    const pageData = {
      name,
      components: components.value,
      canvasConfig: canvasConfig.value,
      pageConfig: { ...pageConfig.value, title: name },
      timestamp: new Date().toISOString(),
    }
    localStorage.setItem(`page_${Date.now()}`, JSON.stringify(pageData))
    return pageData
  }

  // 更新缩放级别
  const setZoomLevel = (level) => {
    zoomConfig.value.level = Math.max(zoomConfig.value.min, Math.min(zoomConfig.value.max, level))
  }

  // 缩放放大
  const zoomIn = () => {
    const newLevel = zoomConfig.value.level + zoomConfig.value.step
    setZoomLevel(newLevel)
  }

  // 缩放缩小
  const zoomOut = () => {
    const newLevel = zoomConfig.value.level - zoomConfig.value.step
    setZoomLevel(newLevel)
  }

  // 重置缩放
  const resetZoom = () => {
    zoomConfig.value.level = 1
  }

  // 适合缩放（根据容器大小自动计算）
  const fitToScreen = (containerWidth, containerHeight, canvasWidth, canvasHeight) => {
    const scaleX = containerWidth / canvasWidth
    const scaleY = containerHeight / canvasHeight
    const scale = Math.min(scaleX, scaleY, 1) // 不超过100%
    setZoomLevel(scale)
  }

  // 缩放到指定比例
  const zoomTo = (level) => {
    setZoomLevel(level)
  }

  // 获取缩放选项
  const getZoomOptions = () => {
    return [
      { label: '25%', value: 0.25 },
      { label: '50%', value: 0.5 },
      { label: '75%', value: 0.75 },
      { label: '100%', value: 1 },
      { label: '125%', value: 1.25 },
      { label: '150%', value: 1.5 },
      { label: '200%', value: 2 },
    ]
  }

  // 获取默认属性
  function getDefaultProps(componentType) {
    const defaultProps = {
      text: { content: '文本内容', fontSize: '14px', color: '#333' },
      button: { text: '按钮', type: 'primary', size: 'default' },
      input: { placeholder: '请输入', type: 'text', size: 'default' },
      image: { src: '', alt: '图片', width: '200px', height: '150px' },
      container: { background: '#fff', padding: '20px', borderRadius: '4px' },
      chart: { type: 'line', title: '图表标题', data: [] },
    }
    return defaultProps[componentType] || {}
  }

  // 获取默认样式
  function getDefaultStyles(componentType) {
    const defaultStyles = {
      text: { textAlign: 'left', fontWeight: 'normal' },
      button: { margin: '5px' },
      input: { width: '200px', margin: '5px' },
      image: { objectFit: 'cover' },
      container: { minHeight: '100px', border: '1px dashed #ccc' },
      chart: { width: '400px', height: '300px' },
    }
    return defaultStyles[componentType] || {}
  }

  // 加载页面
  const loadPage = (pageData) => {
    components.value = pageData.components || []
    canvasConfig.value = pageData.canvasConfig || canvasConfig.value
    pageConfig.value = pageData.pageConfig || pageConfig.value
    selectedComponentId.value = null
    // 重置缩放级别
    resetZoom()
  }

  return {
    // state
    components,
    selectedComponentId,
    canvasConfig,
    pageConfig,
    zoomConfig,

    // getters
    selectedComponent,

    // actions
    addComponent,
    removeComponent,
    updateComponentProps,
    updateComponentStyles,
    updateComponentPosition,
    selectComponent,
    clearSelection,
    clearCanvas,
    savePage,
    loadPage,

    // zoom actions
    setZoomLevel,
    zoomIn,
    zoomOut,
    resetZoom,
    fitToScreen,
    zoomTo,
    getZoomOptions,
  }
})
